//
//  WelcomeThirdView.swift
//  ShouChong
//
//  Created by yw on 2024/9/9.
//

import SwiftUI
import RevenueCat
import Alamofire
import ProgressHUD
import MMDrawerController

struct VipModel:Identifiable {
    var id:String = UUID().uuidString
    var price:String
    var title:String
    var subTitle:String
    var identifier:String
    var discounts:[StoreProductDiscount]
    var package:Package
}

struct WelcomeThirdView: View {
    var reachabilityManager = NetworkReachabilityManager()
    @State private var purchaseItem:VipModel?
    @AppStorage("curren_main_color") var currentMainColor = "color_main_01"
    private struct TitleModel:Identifiable {
        var id:String = UUID().uuidString
        var name:String
        var icon:String
    }
    
    @State private var list:[TitleModel] = [
        TitleModel(name: "不展示广告", icon: "❌"),
        TitleModel(name: "启动更迅速", icon: "⏫"),
        TitleModel(name: "更多主题颜色选择", icon: "🌈"),
        TitleModel(name: "展示会员专属logo", icon: "👑"),
        
    ]
    @State var buttonText:String = ""
    
    var body: some View {
        VStack {
           
            HStack {
                Image(systemName: "xmark")
                    .resizable()
                    .frame(width: 24,height: 24)
                    .foregroundColor(Color("color_gray"))
                    .onTapGesture {
                        closeTap()
                    }
                Spacer()
            }.padding(.horizontal,20)
                .padding(.top,26)
            
            Text("更多会员功能邀您体验")
                .modifier(MainTextModifier(fontSize: 22, fontWeight: .bold, foreColor: Color("color_text_black")))
                .padding(.top,20)
                .padding(.bottom,20)
            
            Image("welcome_third")
                .resizable()
                .frame(width: 200,height: 200)
                .aspectRatio(contentMode: .fit)
                .padding(.horizontal,20)
                .padding(.vertical,20)
            VStack {
                ForEach(list){item in
                    HStack {
                        Text(item.icon)
                            .padding(.trailing,2)
                        Text(item.name)
                            .modifier(MainTextModifier(fontSize: 16, fontWeight: .regular, foreColor: Color("color_text_black")))
                        Spacer()
                    }.padding(.horizontal,20)
                        .padding(.vertical,4)
                }
            }
            
            Spacer()
            if !buttonText.isEmpty {
                
                ShakeButton(label: Text(buttonText).modifier(MainButtonModifier(width: kScreenWidth - 50))
                )  {
                    buy()
                }
                HStack {
                    Text("直接体验")
                        .modifier(MainTextModifier(fontSize: 14, fontWeight: .light, foreColor: Color("color_text_black")))
                        .onTapGesture {
                            closeTap()
                        }
                    RoundedRectangle(cornerRadius: 2)
                        .fill(Color(currentMainColor))
                        .frame(width: 2,height: 16)
                        .padding(.horizontal,3)
                    Text("恢复订阅")
                        .modifier(MainTextModifier(fontSize: 14, fontWeight: .light, foreColor: Color("color_text_black")))
                        .onTapGesture {
                            recoverBuy()
                        }
                }.padding(.bottom,10)
            }
            
        }.onAppear{
            fetchSubscriptionPrices()
        }.onDisappear(perform: {
            reachabilityManager?.stopListening()
        })
    }
    
    private func closeTap() {
        let generator = UIImpactFeedbackGenerator(style: .light)
        generator.prepare()
        generator.impactOccurred()
        goToHome()
    }
    
    private func goToHome() {
        DispatchQueue.main.asyncAfter(deadline: .now() + 0.5) {
            let vc = BaseNavController(rootViewController: HomeViewController())
            let settingVC = OpenNavViewController(rootViewController: SettingViewController())
            let mmVC = MMDrawerController(center: vc, leftDrawerViewController:settingVC)
            mmVC?.openDrawerGestureModeMask = .all
            mmVC?.closeDrawerGestureModeMask = .all
            mmVC?.showsShadow = true
            mmVC?.maximumLeftDrawerWidth = 200
            mmVC?.shadowRadius = 5
            mmVC?.shadowColor = .gray.withAlphaComponent(0.4)
            mmVC?.shouldStretchDrawer = false
            UIApplication.shared.keyWindow?.rootViewController = mmVC
        }
    }
    
    /// 发起订阅
    private func buy() {
//        UserDefaults.standard.setValue(false, forKey: kIsFirstEnterApp)
        guard let purchaseItem = purchaseItem else {
            DPrint("获取订阅信息失败")
            return
        }
        if !purchaseItem.identifier.isEmpty {
//            let currentItem = list.filter { item in
//                return item.id == currentId
//            }
            ProgressHUD.animate("正在订阅...")
            Purchases.shared.purchase(package: purchaseItem.package) { (transaction, customerInfo, error, userCancelled) in
                ProgressHUD.dismiss()
                if customerInfo?.entitlements[kPurchaseName]?.isActive == true {
                    // Unlock that great "pro" content
                    self.checkPurchaseInfo()
                } else {
                    YWToast.show(text: "订阅失败，请重试")
                }
            }
            
        } else {
            YWToast.show(text: "未获取到订阅信息")
        }
        
    }
    
    private func recoverBuy() {
        let generator = UIImpactFeedbackGenerator(style: .light)
        generator.prepare()
        generator.impactOccurred()
        ProgressHUD.animate("加载中")
        Purchases.shared.restorePurchases { customerInfo, error in
            //... check customerInfo to see if entitlement is now active
            
            ProgressHUD.dismiss()
            if customerInfo?.entitlements[kPurchaseName]?.isActive == true {
                // Unlock that great "pro" content
                self.checkPurchaseInfo()
            } else {
                YWToast.show(text: "未获取到订阅信息")
            }
        }
    }
    
    /// 检测订阅状态
    private func checkPurchaseInfo() {
        ProgressHUD.animate("加载中")
        Purchases.shared.getCustomerInfo { customInfo, err in
            ProgressHUD.dismiss()
            guard let customInfo = customInfo, err == nil else {
                YWToast.show(text: "获取订阅数据失败")
                return
            }
            if customInfo.entitlements[kPurchaseName]?.isActive == true {
                print("已经订阅了")
                UserDefaults.standard.set(true, forKey: kVipKey)
                YWToast.show(text: "您已订阅")
                goToHome()
                
            } else {
                print("没有订阅")
//                self.isPruchase = false
                UserDefaults.standard.set(false, forKey: kVipKey)
                self.fetchSubscriptionPrices()
            }
            
        }
    }
    
    // 检索订阅价格
    private func fetchSubscriptionPrices() {
        
        reachabilityManager?.startListening(onUpdatePerforming: { status in
            if status == .reachable(.cellular) || status == .reachable(.ethernetOrWiFi) {
                //        YWProgressHUD.showLoadingHudView(message: NSLocalizedString("purchase_tip_40", comment: ""))
                        Purchases.shared.getOfferings { (offerings, error) in
                            if let packages = offerings?.current?.availablePackages {
                                print("订阅包：\(packages)")
                                // 使用价格更新UI
                                //              self.purchaseBtn.isHidden = false
                //                YWProgressHUD.hideHud()
                                packages.indices.forEach { index in
                                    if packages[index].storeProduct.productIdentifier == "lulemeWeekly" {
                                        let model = VipModel(
                                            price: packages[index].localizedPriceString,
                                            title: packages[index].storeProduct.localizedTitle,
                                            subTitle: packages[index].storeProduct.localizedDescription,
                                            identifier:  packages[index].storeProduct.productIdentifier,
                                            discounts: packages[index].storeProduct.discounts,
                                            package: packages[index])
                                        purchaseItem = model
                                    }
                                }
                                self.buttonText = "以每周\(purchaseItem?.price ?? "")成为会员"
//                                setPurchaseTitleModel()
                //                currentId = list.first?.id ?? ""
                            } else {
                                // 未找到可用的套餐
                                //              self.purchaseBtn.isHidden = true
                                YWToast.show(text: "未找到可用订阅套餐")
                            }
                        }
            }
        })

    }
}

